#include "SD_MMC.h"
#include "esp_vfs_fat.h"
#include <stdio.h>
#define EXAMPLE_MAX_CHAR_SIZE 64
#define MOUNT_POINT "/sdcard"

static const char *SD_TAG = "SD";

uint32_t Flash_Size = 0;
uint32_t SDCard_Size = 0;

// 查找是否有命名文件存在，如果没有存在则创建，有则写入数据
void SD_createFile(const char *name, char *data)
{
   
    FIL file ; // 定义一个指向FIL结构体的指针
    // 检查文件是否存�?
    // char path[EXAMPLE_MAX_CHAR_SIZE];
    // sprintf(path, "%s/%s", MOUNT_POINT, name);
    FRESULT fr = f_stat(name, NULL);
    if (fr == FR_NO_FILE)
    {
        // 文件不存在，创建文件
       // printf("File %s does not exist, creating it\n", path);
        FRESULT  res = f_open(&file, name, FA_OPEN_APPEND | FA_WRITE); // 打开文件，如果文件不存在则创�?
        printf("f_open == %d\n", res);
        char *header = "Time,Temperature,Humidity,\n";
     
        int f = f_puts(header, &file);
        if (f < 0)
        {
            printf("Failed to write header to file\n");
        }
        else
        {
            printf("Header written to file\n");
        }

        f_close(&file); // 关闭文件
    }
    else
    {
        // 文件存在，写入数�?
        printf("fre == %d\n", fr);
    }

}
// 定义一个函数，用于向指定路径的文件写入数据

esp_err_t s_example_read_file(const char *path)
{
    ESP_LOGI(SD_TAG, "Reading file %s", path);
    FILE *f = fopen(path, "r");
    if (f == NULL)
    {
        ESP_LOGE(SD_TAG, "Failed to open file for reading");
        return ESP_FAIL;
    }
    char line[EXAMPLE_MAX_CHAR_SIZE];
    fgets(line, sizeof(line), f);
    fclose(f);

    // strip newline
    char *pos = strchr(line, '\n');
    if (pos)
    {
        *pos = '\0';
    }
    ESP_LOGI(SD_TAG, "Read from file: '%s'", line);

    return ESP_OK;
}

// 获取并打印SD卡剩余容�?
void print_sdcard_free_space()
{
    size_t total = 0, used = 0;
    esp_err_t ret = esp_vfs_fat_info(MOUNT_POINT, &total, &used);
    if (ret != ESP_OK)
    {
        ESP_LOGE(SD_TAG, "Failed to get FAT partition info (%s)", esp_err_to_name(ret));
        return;
    }
    ESP_LOGI(SD_TAG, "SD card total space: %d MB", total / (1024 * 1024));
    ESP_LOGI(SD_TAG, "SD card free space: %d MB", (total - used) / (1024 * 1024));
}

esp_err_t SD_Init(void)
{
    esp_err_t ret;

    // Options for mounting the filesystem.
    // If format_if_mount_failed is set to true, SD card will be partitioned and formatted in case when mounting fails.  false true
    esp_vfs_fat_sdmmc_mount_config_t mount_config = {
        .format_if_mount_failed = true,
        .max_files = 5,
        .allocation_unit_size = 16 * 1024};
    sdmmc_card_t *card;
    const char mount_point[] = MOUNT_POINT;
    ESP_LOGI(SD_TAG, "Initializing SD card");

    // Use settings defined above to initialize SD card and mount FAT filesystem.
    // Note: esp_vfs_fat_sdmmc/sdspi_mount is all-in-one convenience functions.
    // Please check its source code and implement error recovery when developing production applications.
    ESP_LOGI(SD_TAG, "Using SPI peripheral");

    // By default, SD card frequency is initialized to SDMMC_FREQ_DEFAULT (20MHz)
    // For setting a specific frequency, use host.max_freq_khz (range 400kHz - 20MHz for SDSPI)
    // Example: for fixed frequency of 10MHz, use host.max_freq_khz = 10000;
    sdmmc_host_t host = SDMMC_HOST_DEFAULT();

    // This initializes the slot without card detect (CD) and write protect (WP) signals.
    // Modify slot_config.gpio_cd and slot_config.gpio_wp if your board has these signals.
    // 初始化SD卡槽，不包含卡检测（CD）和写保护（WP）信号�?
    // 如果你的板有这些信号，请修改slot_config.gpio_cd和slot_config.gpio_wp�?
    sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT();
    // 设置数据线宽度为1，即1线模式。如果需�?4线模式，可以将此值设置为4�?
    slot_config.width = 1; // 1-wire  / 4-wire   slot_config.width = 4;

    // 设置SD卡的时钟引脚，具体引脚号由CONFIG_EXAMPLE_PIN_CLK定义�?
    slot_config.clk = CONFIG_EXAMPLE_PIN_CLK; // 14
    // 设置SD卡的命令引脚，具体引脚号由CONFIG_EXAMPLE_PIN_CMD定义�?
    slot_config.cmd = CONFIG_EXAMPLE_PIN_CMD; // 17
    // 设置SD卡的数据0引脚，具体引脚号由CONFIG_EXAMPLE_PIN_D0定义�?
    slot_config.d0 = CONFIG_EXAMPLE_PIN_D0; // 16
    // 设置SD卡的数据1引脚，具体引脚号由CONFIG_EXAMPLE_PIN_D1定义�?
    slot_config.d1 = CONFIG_EXAMPLE_PIN_D1;
    // 设置SD卡的数据2引脚，具体引脚号由CONFIG_EXAMPLE_PIN_D2定义�?
    slot_config.d2 = CONFIG_EXAMPLE_PIN_D2;
    // 设置SD卡的数据3引脚，具体引脚号由CONFIG_EXAMPLE_PIN_D3定义�?
    slot_config.d3 = CONFIG_EXAMPLE_PIN_D3;

    // Enable internal pullups on enabled pins. The internal pullups are insufficient however, please make sure 10k external pullups are connected on the bus. This is for debug / example purpose only.
    // 在启用的引脚上启用内部上拉电阻。然而，内部上拉电阻不足，请确保在总线上连�?10k的外部上拉电阻。这仅用于调�?/示例目的�?
    slot_config.flags |= SDMMC_SLOT_FLAG_INTERNAL_PULLUP;

    // 使用ESP_LOGI宏记录信息日志，表示正在挂载文件系统
    ESP_LOGI(SD_TAG, "Mounting filesystem");
    // 调用esp_vfs_fat_sdmmc_mount函数挂载FAT文件系统到指定的挂载�?
    // 参数分别为：挂载点、主机配置、插槽配置、挂载配置和SD卡信息结构体
    ret = esp_vfs_fat_sdmmc_mount(mount_point, &host, &slot_config, &mount_config, &card);

    // 检查挂载操作是否成�?
    if (ret != ESP_OK)
    {
        // 如果返回值为ESP_FAIL，表示挂载失�?
        if (ret == ESP_FAIL)
        {
            // 使用ESP_LOGE宏记录错误日志，提示用户如果需要格式化SD卡，需要设置相应的配置选项
            ESP_LOGE(SD_TAG, "Failed to mount filesystem. "
                             "If you want the card to be formatted, set the CONFIG_EXAMPLE_FORMAT_IF_MOUNT_FAILED menuconfig option.");
        }
        else
        {
            // 如果返回值不是ESP_FAIL，表示初始化SD卡失�?
            // 使用ESP_LOGE宏记录错误日志，提示用户确保SD卡线路有上拉电阻，并打印错误原因
            ESP_LOGE(SD_TAG, "Failed to initialize the card (%s). "
                             "Make sure SD card lines have pull-up resistors in place.",
                     esp_err_to_name(ret));
        }
        // 返回，结束函数执�?
        return ret;
    }
    // 使用ESP_LOGI宏记录信息日志，表示文件系统已成功挂�?
    ESP_LOGI(SD_TAG, "Filesystem mounted");

    // Card has been initialized, print its properties
    sdmmc_card_print_info(stdout, card);
    print_sdcard_free_space();

    return ESP_OK;
}

// 定义一个函数Open_File，用于打开文件
FILE *Open_File(const char *file_path)
{
    // 使用ESP_LOGI宏记录信息日志，表示正在尝试打开文件，并输出文件路径
    ESP_LOGI(SD_TAG, "Attempting to open file: %s", file_path);
    // 使用fopen函数尝试以二进制读模�?("rb")打开文件，并将返回的文件指针赋值给fp
    FILE *fp = fopen(file_path, "rb"); // Open the MP3 file in binary mode
    // 检查文件指针fp是否为NULL，如果是NULL表示文件打开失败
    if (fp == NULL)
    {
        // 使用ESP_LOGE宏记录错误日志，输出文件路径和错误信�?
        ESP_LOGE(SD_TAG, "Failed to open file %s. Error: %s", file_path, strerror(errno));
    }
    else
        // 如果文件打开成功，使用printf函数输出成功信息
        printf("File %s was successfully opened. \r\n", file_path);
    // 返回文件指针fp，无论成功与�?
    return fp;
}

#define MAX_FILE_NAME_SIZE 100 // Define maximum file name size
#define MAX_PATH_SIZE 512      // Define a larger size for the full path
uint16_t Folder_retrieval(const char *directory, const char *fileExtension, char File_Name[][MAX_FILE_NAME_SIZE], uint16_t maxFiles)
{
    DIR *dir = opendir(directory); // Opens the specified directory
    if (dir == NULL)
    {
        ESP_LOGE(SD_TAG, "Path: <%s> does not exist", directory);
        return 0;
    }

    uint16_t fileCount = 0; // File counter
    struct dirent *entry;   // Directory entry pointer

    // 遍历目录中的所有条�?
    while ((entry = readdir(dir)) != NULL && fileCount < maxFiles)
    {
        // Skip "." and ".." Special directory
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
        {
            continue;
        }

        const char *dot = strrchr(entry->d_name, '.');
        if (dot != NULL && dot != entry->d_name)
        {

            if (strcasecmp(dot, fileExtension) == 0)
            {

                strncpy(File_Name[fileCount], entry->d_name, MAX_FILE_NAME_SIZE - 1);
                File_Name[fileCount][MAX_FILE_NAME_SIZE - 1] = '\0';

                char filePath[MAX_PATH_SIZE];
                snprintf(filePath, MAX_PATH_SIZE, "%s/%s", directory, entry->d_name);

                printf("File found: %s\r\n", filePath);
                fileCount++;
            }
        }
        else
        {
            // If the extension name is not found, you can output debugging information
            // printf("No extension found for file: %s\r\n", entry->d_name);
        }
    }

    closedir(dir); //

    if (fileCount > 0)
    {
        ESP_LOGI(SD_TAG, "Retrieved %d files with extension '%s'", fileCount, fileExtension); //
    }
    else
    {
        ESP_LOGW(SD_TAG, "No files with extension '%s' found in directory: %s", fileExtension, directory); //
    }

    return fileCount;
}